﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;

using Newtonsoft.Json;
using MxTol.UI.Helpers;
using MxTol.Managers;
using MxTol.Models;

namespace MxTol.UI.Controllers
{
    // 权限(系统管理员)管理 
    public class AdminsManagementController : Controller
    {
        private const string MIME_TYPE = "application/json;charset=utf-8;";

        #region View

        // 获取所有系统管理员页面
        public ActionResult GetAllAdminsView()
        {
            if (Session["account"] == null)
            {
                string script = string.Format("<script>window.top.location='{0}'</script>", ConfigurationManager.AppSettings["LoginUrl"]);
                return Content(script);
            }
            else
            {
                return View();
            }
        }

        // 添加管理员页面
        public ActionResult AddAdminView()
        {
            if (Session["account"] == null)
            {
                string script = string.Format("<script>window.top.location='{0}'</script>", ConfigurationManager.AppSettings["LoginUrl"]);
                return Content(script);
            }
            else
            {
                return View();
            }
        }

        // 查询管理员页面
        public ActionResult QueryAdminView()
        {
            if (Session["account"] == null)
            {
                string script = string.Format("<script>window.top.location='{0}'</script>", ConfigurationManager.AppSettings["LoginUrl"]);
                return Content(script);
            }
            else
            {
                return View();
            }
        }

        // 修改个人信息页面(导航栏的修改个人信息按钮)
        public ActionResult GetAdminInfoView()
        {
            if (Session["account"] == null)
            {
                string script = string.Format("<script>window.top.location='{0}'</script>", ConfigurationManager.AppSettings["LoginUrl"]);
                return Content(script);
            }
            else
            {
                Admin admin = null;
                try
                {
                    admin = Admin.GetAdminByAccount(Session["account"].ToString());
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLogAsync("查看管理员个人信息Action失败", ex);
                }

                if (admin != null)
                {
                    return View(admin);
                }
                else
                {
                    return Content("获取个人信息失败");
                }
            }
        }

        // 修改密码页面
        public ActionResult UpdatePswordView()
        {
            return View();
        }

        // 修改个人信息页面(用于弹出修改管理员窗体页面)
        public ActionResult UpdateAdminInFrameView()
        {
            Admin admin = null;
            try
            {
                string id = Request["id"];
                admin = Admin.GetAdminByID(new Guid(id));
            }
            catch (Exception ex)
            {
                LogHelper.WriteLogAsync("获取需要更新的管理员信息失败", ex);
            }

            if (admin != null)
            {
                if (admin.Level == 2)
                {
                    if (Session["account"].ToString() == admin.Account)
                    {
                        return View(admin);
                    }
                    else
                    {
                        return Content("对不起，您没有权限进行此操作");
                    }
                }
                else
                {
                    return View(admin);
                }
            }
            else
            {
                return Content("获取需要更新的管理员信息失败");
            }
        }

        #endregion

        #region 功能

        // 系统登录处理
        public ActionResult Login()
        {

            // 0：异常失败  1：账号不存在   2：密码错误   3：成功
            int flag = 0;
            try
            {
                string account = Request["a"];
                string psword = Request["p"];

                // 账号存在
                if (AdminManager.IsAccountExsit(account))
                {
                    // 密码正确
                    if (AdminManager.IsPswordMatch(account, psword))
                    {
                        flag = 3;
                    }
                    else
                    {
                        flag = 2;
                    }
                }
                else
                {
                    flag = 1;
                }
            }
            catch (Exception ex)
            {
                flag = 0;
                LogHelper.WriteLogAsync("管理员登录系统时发生错误", ex);
            }

            return Content(flag.ToString(), MIME_TYPE);
        }

        // 获取所有管理员(以Json分页数据格式返回)
        public ActionResult GetAdminsJson()
        {
            string json = EasyuiHelper.DefaultJson;
            try
            {
                string currentPage = Request["page"];
                string pageSize = Request["rows"];

                json = AdminManager.GetAllAdmin(int.Parse(currentPage), int.Parse(pageSize));
            }
            catch (Exception ex)
            {
                json = EasyuiHelper.DefaultJson;
                LogHelper.WriteLogAsync("获取管理员Json格式数据错误", ex);
            }
            return Content(json, MIME_TYPE);
        }

        // 添加管理员
        public ActionResult AddAdmin()
        {
            // 0：异常失败  1：姓名已存在   2：电话号码已存在  3:账号已存在  4：成功
            int flag = 0;
            try
            {
                string name = Request["name"];
                string phone = Request["phone"];
                string account = Request["account"];
                string psword = Request["psword"];
                string level = Request["level"];

                // 姓名不存在
                if (!AdminManager.IsNameExist(name))
                {
                    // 号码不存在
                    if (!AdminManager.IsPhoneExist(phone))
                    {
                        // 账号不存在
                        if (!AdminManager.IsAccountExsit(account))
                        {
                            // 添加新管理员
                            Admin admin = new Admin();

                            admin.Name = name;
                            admin.Phone = phone;
                            admin.Account = account;
                            admin.Psword = MD5Helper.MD5(psword);
                            admin.AddTime = DateTime.Now;
                            admin.Level = int.Parse(level);

                            admin.Save();
                            flag = 4;
                        }
                        else
                        {
                            flag = 3;
                        }
                    }
                    else
                    {
                        flag = 2;
                    }
                }
                else
                {
                    flag = 1;
                }
            }
            catch (Exception ex)
            {
                flag = 0;
                LogHelper.WriteLogAsync("添加管理员失败", ex);
            }

            return Content(flag.ToString(), MIME_TYPE);
        }

        // 删除管理员
        public ActionResult DeleteAdmin()
        {
            // 0:异常失败  1：系统管理员  2：成功
            int flag = 0;
            try
            {
                string id = Request["id"];
                Admin admin = Admin.GetAdminByID(new Guid(id));
                if (admin != null)
                {
                    if (admin.Level == 2)
                    {
                        flag = 1;
                    }
                    else
                    {
                        admin.Delete();
                        flag = 2;
                    }
                }
            }
            catch (Exception ex)
            {
                flag = 0;
                LogHelper.WriteLogAsync("删除管理员失败", ex);
            }
            return Content(flag.ToString(), MIME_TYPE);
        }

        // 更新管理员
        public ActionResult UpdateAdmin()
        {
            // 0：异常失败  1：姓名已存在   2：电话号码已存在  3:账号已存在  4：成功
            int flag = 0;
            try
            {
                string id = Request["id"];
                string name = Request["name"];
                string phone = Request["phone"];
                string account = Request["account"];
                string level = Request["level"];

                // 需要更新的管理员
                Admin admin = Admin.GetAdminByID(new Guid(id));


                // 新姓名
                if (name != admin.Name)
                {
                    // 新姓名存在
                    if (AdminManager.IsNameExist(name))
                    {
                        return Content("1", MIME_TYPE);
                    }
                }

                // 新电话号码
                if (phone != admin.Phone)
                {
                    //新号码存在
                    if (AdminManager.IsPhoneExist(phone))
                    {
                        return Content("2", MIME_TYPE);
                    }
                }

                // 新账号
                if (account != admin.Account)
                {
                    // 新账号存在
                    if (AdminManager.IsAccountExsit(account))
                    {
                        return Content("3", MIME_TYPE);
                    }
                }

                // 更新管理员信息
                admin.Name = name;
                admin.Phone = phone;
                admin.Account = account;
                admin.Level = int.Parse(level);
                admin.Update();
                flag = 4;
            }
            catch (Exception ex)
            {
                flag = 0;
                LogHelper.WriteLogAsync("更新管理员失败", ex);
            }

            return Content(flag.ToString(), MIME_TYPE);
        }

        // 查询管理员
        public ActionResult QueryAdmin()
        {
            string json = EasyuiHelper.DefaultJson;
            try
            {
                string name = Request["name"];
                string phone = Request["phone"];
                string account = Request["account"];
                string level = Request["level"];

                // 全部搜索
                int currentPage = 1;
                string pageSize = Request["rows"];

                // 拼接sql基本查询字段
                string sql_base = "select * from Admin";
                string sql_where = string.Empty;
                if (!string.IsNullOrEmpty(name))
                {
                    sql_where += string.Format("and name like '%{0}%' ", name);
                }
                if (!string.IsNullOrEmpty(phone))
                {
                    sql_where += string.Format("and phone = '{0}' ", phone);
                }
                if (!string.IsNullOrEmpty(account))
                {
                    sql_where += string.Format("and account like '%{0}%' ", account);
                }
                if (level != "3")
                {
                    sql_where += string.Format("and level = '{0}' ", level);
                }

                // 有查询条件，没有查询所有
                string sql = sql_base;
                if (sql_where.Length != 0)
                {
                    // 去掉第一个"and"
                    if ((sql_where.TrimStart()).StartsWith("and"))
                    {
                        sql_where = sql_where.Substring(3, sql_where.Length - 3);
                        sql = sql_base + " where " + sql_where;
                    }
                }
                json = AdminManager.GetAllAdmin(currentPage, int.Parse(pageSize), sql);
            }
            catch (Exception ex)
            {
                json = EasyuiHelper.DefaultJson;
                LogHelper.WriteLogAsync("查询管理员错误", ex);
            }
            return Content(json, MIME_TYPE);
        }

        // 密码重置(密码为电话号码)
        public ActionResult ResetPsword()
        {
            if (Session["account"] == null)
            {
                string script = string.Format("<script>window.top.location='{0}'</script>", ConfigurationManager.AppSettings["LoginUrl"]);
                return Content(script);
            }

            // 0：异常失败  1：系统管理员   2：成功
            int flag = 0;
            try
            {
                string id = Request["id"];
                Admin admin = Admin.GetAdminByID(new Guid(id));
                if (admin != null)
                {
                    if (admin.Level == 2)
                    {
                        if (admin.Account == Session["account"].ToString())
                        {
                            admin.Psword = MD5Helper.MD5(admin.Phone);
                            admin.Save();
                            flag = 2;
                        }
                        else
                        {
                            flag = 1;
                        }
                    }
                    else
                    {
                        admin.Psword = MD5Helper.MD5(admin.Phone);
                        admin.Save();
                        flag = 2;
                    }
                }
            }
            catch (Exception ex)
            {
                flag = 0;
                LogHelper.WriteLogAsync("重置管理员密码失败", ex);
            }
            return Content(flag.ToString(), MIME_TYPE);
        }

        // 修改密码
        public ActionResult UpdatePsword()
        {
            // 0：服务器内部异常   1：密码长度少于6或大于20   2：旧密码错误   3：修改成功
            int flag = 0;

            try
            {
                string id = Request["id"];
                string old_psword = Request["oldps"];
                string new_psword = Request["newps"];

                if (new_psword.Length > 6 || new_psword.Length < 20)
                {
                    Admin admin = Admin.GetAdminByID(new Guid(id));
                    if (admin != null)
                    {
                        if (old_psword.ToLower() == admin.Psword)
                        {
                            admin.Psword = new_psword.ToLower();
                            admin.Save();
                            flag = 3;
                        }
                        else
                        {
                            flag = 2;
                        }
                    }
                }
                else
                {
                    flag = 1;
                }
            }
            catch (Exception ex)
            {
                flag = 0;
                LogHelper.WriteLogAsync("修改管理员密码错误", ex);
            }

            return Content(flag.ToString(), MIME_TYPE);
        }

        #endregion
    }
}
